package com.rjwh.dingdong.client.activity.guide;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;

import com.rjwh.dingdong.client.activity.BaseActivity;
import com.rjwh.dingdong.client.activity.community.CommunityPostDetailActivity;
import com.rjwh.dingdong.client.application.MyApplication;
import com.rjwh.dingdong.client.constant.LocalConstant;
import com.rjwh.dingdong.client.mvp.presenter.impl.SplashPresenter;
import com.rjwh.dingdong.client.mvp.view.SplashView;
import com.rjwh.dingdong.client.util.AppUtil;
import com.rjwh.dingdong.client.util.DeviceUuidFactory;
import com.rjwh.dingdong.client.util.LogUtil;
import com.rjwh.dingdong.client.util.OTGInster;
import com.rjwh.dingdong.client.util.PermissionUtil;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 启动界面
 *
 * @author 王小珂
 * @ClassName SplashActivity
 * @Description TODO(这里用一句话描述这个类的作用)
 * @date 2015-10-20 上午10:38:52
 * @history 1.YYYY-MM-DD
 * author:
 * description:
 */
public class SplashActivity extends BaseActivity implements PermissionUtil.PermissionCallBack, SplashView {
    private Context ctx;

    private AlertDialog alertDialogPermission;
    private AlertDialog errorDialogPermission;
    private SplashPresenter presenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.splash_layout);
        LogUtil.e("SplashActivity", "SplashActivity onCreate");
        ctx = this;
        presenter = new SplashPresenter(this,this);
        requestPermissions();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            this.finish();
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onRestart() {
        super.onRestart();
        LogUtil.e("SplashActivity", "onRestart");
        requestPermissions();
    }

    @Override
    public void onPermissionGetSuccess() {
        if (!MyApplication.spUtil.getBoolPreferenceByParamName(ctx,
                LocalConstant.SP_IS_LOGINED)) {
            MyApplication.spUtil.setStrPreference(MyApplication.app, LocalConstant.SP_BABYID, "0");
            MyApplication.spUtil.setStrPreference(MyApplication.app, LocalConstant.SP_USERID, "0");
        }
        presenter.doAppStartUp();
        LogUtil.e("SplashActivity", "onPermissionGetSuccess");
        Observable.create(new Observable.OnSubscribe<Long>() {
            @Override
            public void call(Subscriber<? super Long> subscriber) {

                if (MyApplication.getInstance().spUtil.getStrPreferenceByParamName(SplashActivity.this, LocalConstant.SP_UUID).equals("")) {
                    String deviceId = DeviceUuidFactory.getUUID(SplashActivity.this);
                    LogUtil.e("SplashActivity", "deviceId: " + deviceId);
                    MyApplication.spUtil.setStrPreference(SplashActivity.this, LocalConstant.SP_UUID, deviceId);
                    MyApplication.deviceId = deviceId;
                }
//                copyAssect();
                subscriber.onNext(1l);
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.newThread())
                .flatMap(new Func1<Long, Observable<Long>>() {

                    @Override
                    public Observable<Long> call(Long aLong) {
                        return Observable.timer(2, TimeUnit.SECONDS, AndroidSchedulers.mainThread());
                    }
                })
                .subscribe(new Action1<Long>() {
                    @Override
                    public void call(Long aLong) {

                        boolean isGuideShown = MyApplication.spUtil.getBoolPreferenceByParamName(MyApplication.getInstance(), LocalConstant.SP_IS_GUIDE_SHOWN, false);
                        LogUtil.e("SplashActivity", "isGuideShown:" + isGuideShown);
                        //如果第一次进入app则进入引导页,否则进入主页
                        if (!isGuideShown) {
                            toGuideActivity();
                        } else {
                            toMainActivty();
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtil.d("SplashActivity", "observable error: " + throwable.getMessage());
                    }
                });
    }

    /**
     * 首次进入app展示引导页
     */
    private void toGuideActivity() {
        Intent intentGuide = new Intent(ctx, GuideActivity.class);
        startActivity(intentGuide);
        SplashActivity.this.finish();
    }

//    @Override
//    protected void onNewIntent(Intent intent) {
//        super.onNewIntent(intent);
//        if (intent != null) {
//            Uri uri = intent.getData();
//            String filepath = uri.getQueryParameter("filepath");
//            Log.e("SplashActivity", "uri:   " + uri.toString());
//            intent.putExtra("url", filepath);
//            intent.setClass(this, CommunityPostDetailActivity.class);
//            startActivity(intent);
//        }
//    }

    @Override
    public void onPermissionGetFail() {
        this.finish();
    }

    @Override
    protected void onDestroy() {
        LogUtil.e("SplashActivity", "onDestroy");
        closePermissionDialog();
        super.onDestroy();
        presenter.detachView();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        LogUtil.e("SplashActivity", "onPause");
    }

    private void toMainActivty() {
//        if (!MyApplication.spUtil.getBoolPreferenceByParamName(ctx,
//                LocalConstant.SP_IS_LOGINED)) {
//            MyApplication.spUtil.setStrPreference(MyApplication.app, LocalConstant.SP_BABYID, "0");
//            MyApplication.spUtil.setStrPreference(MyApplication.app, LocalConstant.SP_USERID, "0");
//        }
        Intent intentMain = new Intent(ctx, MainActivity.class);
        Uri uri = getIntent().getData();
        //判断程序启动是否传递了参数
        if (getIntent().getBundleExtra(LocalConstant.APP_EXTRA_BUNDLE) != null) {
            intentMain.putExtra(LocalConstant.APP_EXTRA_BUNDLE,
                    getIntent().getBundleExtra(LocalConstant.APP_EXTRA_BUNDLE));
        }

        if (uri != null) {
            MyApplication.spUtil.setBoolPreference(this, LocalConstant.SP_MAINPAGE_DAILOG_SHOW,false);
            Intent intentToActivty = null;
            String forwordType = uri.getQueryParameter("subtype");
            LogUtil.e("SplashActivity", "uri: " + uri.toString());

            if (forwordType.equals(LocalConstant.SCHEME_FORWORD_TYPE_COMMUNITY_DETAIL)) {
                intentToActivty = new Intent(ctx, CommunityPostDetailActivity.class);
                String filepath = uri.getQueryParameter("filepath");
                String topicid = uri.getQueryParameter("topicid");
                intentToActivty.putExtra("url", filepath + "?userid=" + MyApplication.spUtil.getStrPreferenceByParamName(this, LocalConstant.SP_USERID) + "&platform=ANDROID" + "&version=" + MyApplication.versionCode + "&udid=" + MyApplication.deviceId + "&babyid=" + MyApplication.spUtil.getStrPreferenceByParamName(this, LocalConstant.SP_BABYID) + "&token=" + MyApplication.spUtil.getStrPreferenceByParamName(this, LocalConstant.SP_USER_TOKEN));
                intentToActivty.putExtra("topicid", topicid);
            }

            if (intentToActivty == null) {
                LogUtil.e("HTML", "SplashActivity intentToActivty==NULL");
                startActivity(intentMain);
            } else {
                LogUtil.e("HTML", "SplashActivity intentArgs");
                Intent[] intentArgs = {intentMain, intentToActivty};
                startActivities(intentArgs);
            }
        } else {
            MyApplication.spUtil.setBoolPreference(this, LocalConstant.SP_MAINPAGE_DAILOG_SHOW,true);
            LogUtil.e("HTML", "SplashActivity intentMain");
            startActivity(intentMain);
        }
        SplashActivity.this.finish();
    }


    public void copyAssect() {
        boolean otgInit = MyApplication.spUtil.getBoolPreferenceByParamName(ctx,
                LocalConstant.SP_OTG_INIT);
        LogUtil.d("otgInit:" + otgInit);
        if (!otgInit) {
            OTGInster.initData(this);
            MyApplication.spUtil.setBoolPreference(ctx,
                    LocalConstant.SP_OTG_INIT, true);
        }
    }

    private void showPermissionDailog(final Context context, final HashMap<String, String> deniedPermissions) {

        final String[] keys = deniedPermissions.keySet().toArray(new String[deniedPermissions.keySet().size()]);
        String[] values = deniedPermissions.values().toArray(new String[deniedPermissions.values().size()]);

        alertDialogPermission = new AlertDialog.Builder(context)
                .setTitle("为了您能正常使用丁冬宝贝,需要以下权限")
                .setItems(values, null)
                .setPositiveButton("下一步", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        try {
                            RxPermissions.getInstance(context)
                                    .request(keys)
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(new Action1<Boolean>() {
                                        @Override
                                        public void call(Boolean aBoolean) {
                                            if (aBoolean) {
                                                onPermissionGetSuccess();
                                            } else {
                                                showPermissionError(context);
                                            }
                                        }
                                    }, new Action1<Throwable>() {
                                        @Override
                                        public void call(Throwable throwable) {
                                            LogUtil.d("SplashActivity", "observable error: " + throwable.getMessage());
                                        }
                                    });
                        } catch (Exception e) {
                            showPermissionError(context);
                            e.printStackTrace();
                        }

                    }
                })
                .setCancelable(false).create();
        if (!isFinishing() && !alertDialogPermission.isShowing()) alertDialogPermission.show();
    }

    /**
     * 权限被拒绝后弹窗,让用户手动去设置
     */
    public void showPermissionError(final Context context) {
        errorDialogPermission = new AlertDialog.Builder(context)
                .setTitle("请允许获取权限")
                .setMessage("由于丁冬宝贝无法获取所需要的权限,不能正常运行,请开启权限后再使用丁冬宝贝." +
                        "设置路径:系统设置->丁冬宝贝->权限")
                .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        AppUtil.startAppDetailSetting(context);
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        onPermissionGetFail();
                    }
                })
                .setCancelable(false).create();

        if (!isFinishing() && !errorDialogPermission.isShowing()) errorDialogPermission.show();
    }


    public void requestPermissions() {
        if (!AppUtil.isOverMarshmallow()) {
            LogUtil.e("SplashActivity", "isOverMarshmallow");
            onPermissionGetSuccess();
            return;
        }
        HashMap<String, String> deniedPermissions = null;

        deniedPermissions = PermissionUtil.getInstance().findDeniedPermissions(this);

        if (deniedPermissions != null && deniedPermissions.size() > 0) {
            showPermissionDailog(this, deniedPermissions);

        } else {
            onPermissionGetSuccess();
            LogUtil.e("permission", "权限已获取！");
        }
    }

    public void closePermissionDialog() {
        if (alertDialogPermission != null && alertDialogPermission.isShowing()) {
            alertDialogPermission.dismiss();
            alertDialogPermission = null;
        }
        if (errorDialogPermission != null && errorDialogPermission.isShowing()) {
            errorDialogPermission.dismiss();
            errorDialogPermission = null;
        }
    }
}
